﻿var Ax = Ax || {};

Ax.post = function(_url, _data, onSuccess, onError) 
{
    return $.ajax(
    {
        type: 'POST',
        url: _url,
        data: _data,
        success: function (result) {
            try
            {
                if(typeof result.success !== "undefined")
                {
                    if(!result.success)
                    {
                        if(onError)
                        {
                            onError(result);
                            onSuccess = 0; // Evita que se ejecute el onSuccess
                        }
                    }
                }
                if(onSuccess)
                    onSuccess(result);
            }
            catch(ex)
            {
                if(onError)
                    onError(Ax.makeAjaxError(100,"exception",ex.message ,ex));
            }
        },
        error: function(xhr, thrownError)
        {
            var msg = "";
            if(typeof thrownError !== "undefined")
                msg = String(thrownError);
            else
                msg = "Unknown exception";
                
            if(onError)
                onError(Ax.makeAjaxError(100, "ajax error", msg, null));
        },
        async: true
    });
};

Ax.makeAjaxError = function(_id, _type, _error, _obj)
{
    return { id:_id, error:_error, success:false, obj:_obj, type:_type };
};